import base64
import urllib

import redis
import requests
from flask import Blueprint, request, jsonify, make_response, redirect
from utils.captcha.captcha import captcha
from utils.redisconn import r
from db import db1, DB
from utils.jwttoken import myjwt
from utils.get_code import get_code
import json
import time
import hmac
from hashlib import sha256

bp_reg = Blueprint('reg', __name__)


# 发送短信验证码接口
@bp_reg.route('/send_sms')
def send_sms():
    # 获取图片验证码的key
    uuid = request.args.get('uuid')
    # 获取图片验证码
    code = request.args.get('code')
    # 获取手机号
    phone = request.args.get('mobile')
    res = get_code('rly', phone, uuid, code)
    return jsonify(json.loads(res))


# 生成图片验证码
@bp_reg.route('/getpic_code')
def getpic_code():
    uuid = request.args.get('uuid')
    name, text, image = captcha.generate_captcha()
    res = make_response(image)
    res.content_type = 'image/png'
    # 图片验证码信息存入redis
    r.set_str(uuid, text, 120)
    return res


#  手机号验证登录
@bp_reg.route('/SmsLogin', methods=['POST'])
def SmsLogin():
    # 获取手机号
    mobile = request.form.get('mobile')
    # 获取验证码
    code = request.form.get('mcode')

    r=redis.Redis(decode_responses=True)
    if r.get(mobile) != None:
        # 获取redis 中的验证码
        redis_code = str(r.get(mobile))
        # 比对操作
        if str(code) == str(redis_code):
            # 验证码通过
            # 查询数据库
            sql = "select id,username,login_hours from user where mobile='%s'" % mobile
            user = db1.find(sql)
            if user:
                # 加密操作
                token = myjwt.jwt_encode(user)
                db = DB()
                print({'code': 200, 'msg': '登陆成功', 'username': user['username'], 'id': user['id'], 'token': token,'login_hours':user['login_hours']})
                return jsonify(
                    {'code': 200, 'msg': '登陆成功', 'username': user['username'], 'id': user['id'], 'token': token,'login_hours':user['login_hours'],'account_one':user['account_one']})
            else:
                # 帮助用户自动注册账号
                # 保存入库
                sql = "insert into user (username,mobile) values('%s','%s')" % (mobile, mobile)
                db1.update(sql)
                # 查询用户信息
                sql1 = "select id,username,login_hours,account_one from user where mobile='%s'" % mobile
                user = db1.find(sql1)
                db = DB()
                # 加密操作
                token = myjwt.jwt_encode(user)
                print( {'code': 200, 'msg': '登录成功', 'username': user['username'], 'id': user['id'], 'token': token,'login_hours':user['login_hours'],'account_one':user['account_one']})
                return jsonify(
                    {'code': 200, 'msg': '登录成功', 'username': user['username'], 'id': user['id'], 'token': token,'login_hours':user['login_hours'],'account_one':user['account_one']})
        else:
            # 比对失败
            return jsonify({'code': 405, 'msg': '您的验证码有误'})
    else:
        return jsonify({'code': 4050, 'msg': '您的验证码已过期,请稍后再试'})


# 拼接url
# 构造钉钉登录url
@bp_reg.route('/dingding_url')
def ding_url():
    appid = 'dingoaukgkwqknzjvamdqh'
    redirect_uri = 'http://localhost:5000/ding_back'
    print({'url':'https://oapi.dingtalk.com/connect/qrconnect?appid=' + appid + '&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=' + redirect_uri})
    return ({'url':'https://oapi.dingtalk.com/connect/qrconnect?appid=' + appid + '&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=' + redirect_uri})


# 第三方登录
@bp_reg.route('/ding_back')
def ding_back():
    # 获取code
    code = request.args.get("code")
    print(code)
    t = time.time()
    # 时间戳
    timestamp = str((int(round(t * 1000))))
    appSecret = 'ly-AzMKMmCKQP3geaILT_An32kEfKO3HeOtApy5CgKwjytevVZC0WYsT2gxMB160'
    # 构造签名
    signature = base64.b64encode(
        hmac.new(appSecret.encode('utf-8'), timestamp.encode('utf-8'), digestmod=sha256).digest())
    # 请求接口，换取钉钉用户名
    payload = {'tmp_auth_code': code}
    headers = {'Content-Type': 'application/json'}
    res = requests.post('https://oapi.dingtalk.com/sns/getuserinfo_bycode?signature=' + urllib.parse.quote(
        signature.decode("utf-8")) + "&timestamp=" + timestamp + "&accessKey=dingoaukgkwqknzjvamdqh",
                        data=json.dumps(payload), headers=headers)
    res_dict = res.json()

    print(res_dict)
    # return jsonify(res.text)
    nick = res_dict['user_info']['nick']
    #  查询用户是否用该钉钉登陆过
    sql = "select id,username from user where username='%s'" % nick
    user = db1.find(sql)
    if user:
        # 加密操作
        token = myjwt.jwt_encode(user)
        return jsonify({'code': 200, 'msg': '登陆成功', 'username': user['username'], 'id': user['id'], 'token': token})
    else:
        # 帮助用户自动注册账号
        # 保存入库
        sql1 = "insert into user (username) values ('%s')" % nick
        # 保存
        db1.update(sql1)
        sql2 = "select id,username from user where username='%s'" % nick
        res2 = db1.find(sql2)
        # 加密操作
        token = myjwt.jwt_encode(res2)
        return jsonify({'code': 200, 'msg': '登录成功', 'username': res2['username'], 'id': res2['id'], 'token': token})


# 微博登录
@bp_reg.route('/weiboCallback')
def weiboCallback():
    code = request.args.get('code')
    # 微博认证地址
    access_token_url = "https://api.weibo.com/oauth2/access_token"
    # 参数
    response = requests.post(access_token_url, data={
        "client_id": '3648830690',
        "client_secret": "916d80b477ccffce5d70e63b02bb1092",
        "grant_type": "authorization_code",
        "code": code,
        "redirect_uri": "http://127.0.0.1:8000/users/weiboCallback/",
    })
    res = eval(str(response.text))
    try:
        uid = res['uid']
        token1 = res['access_token']
    except:
        uid = 0
        # 跳转到错误页面
        return redirect('http://localhost:8080/error_r')
    # 通过uid 去三方登录表中查询,如果存在userid
    sql = 'select u.id,u.mobile from thirdparty as sf inner join user as u on sf.user_id=u.id where uid={}'.format(
        int(uid))
    dd = db1.find(sql)
    if dd:
        # 找到生成的token返回
        # data = {'data':{"id":dd['id'],"mobile":dd['mobile'],"iat":time.time(),"exp":3600}}
        # token = jwte.jwt_en(data)
        return redirect('http://localhost:8080/uid_login?type=1&id=' + str(dd['id']) + '&mobile=' + dd[
            'mobile'] + '&token=' + token1)
    else:
        # 不存在绑定用户操作,redirect 跳转到vue页面,uid,token
        return redirect('http://localhost:8080/uid_login?type=2&uid=' + uid + '&token=' + token1)
